package com.yyt.yytcodesandbox.utils;

import cn.hutool.core.date.StopWatch;
import com.yyt.yytcodesandbox.model.ExecuteMessage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ProcessUtils {

    public static ExecuteMessage runProcessAndGetMessage(Process process,String op){
        ExecuteMessage executeMessage=new ExecuteMessage();
        try {
            StopWatch stopWatch=new StopWatch();
            stopWatch.start();
            //等待程序执行结束
            int exitValue = process.waitFor();
            //exitValue为0为正常
            if(exitValue==0){
                executeMessage.setExitValue(exitValue);
                System.out.println(op+"成功");
                //分批获得进程的信息
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                StringBuilder stringBuilder=new StringBuilder();
                String outputLine;
                while((outputLine= bufferedReader.readLine())!=null){
                    stringBuilder.append(outputLine);
                }
                executeMessage.setMessage(stringBuilder.toString());
            }else{
                executeMessage.setExitValue(exitValue);
                System.out.println(op+"失败，错误码"+exitValue);
                //分批获得进程的正常信息
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                StringBuilder stringBuilder=new StringBuilder();
                String outputLine;
                while((outputLine= bufferedReader.readLine())!=null){
                    stringBuilder.append(outputLine);
                }
                executeMessage.setMessage(stringBuilder.toString());
                //分批获得错误信息
                BufferedReader errorBufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                StringBuilder errorStringBuilder=new StringBuilder();
                String errorOutputLine;
                while((errorOutputLine= errorBufferedReader.readLine())!=null){
                    errorStringBuilder.append(errorOutputLine);
                }
                executeMessage.setErrorMessage(errorStringBuilder.toString());
            }
            stopWatch.stop();
            executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
        } catch (InterruptedException | IOException e) {
            throw new RuntimeException(e);
        }
        return executeMessage;
    }

}
